﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;

namespace LevsSimulator
{
    public partial class MainForm : Form
    {
        private SerialPort serialPort;
        public MainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            serialPort = new SerialPort
            {
                BaudRate = 9600,
                DataBits = 8,
                StopBits = StopBits.One,
                ReadBufferSize = 10240,
                ReadTimeout = 1000,
                WriteTimeout = 1000,
                ReceivedBytesThreshold = 1
            };
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.PortName = "COM5";
            serialPort.Open();

            cmbCommand.DataSource = CreateCommands();
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            this.BeginInvoke(new Action(() =>
            {
                System.Threading.Thread.Sleep(200);
                var strToRead = serialPort.ReadExisting();
                if (string.IsNullOrEmpty(strToRead))
                {
                    return;
                }
                rtbOutput.AppendText("recv:" + strToRead + "\r\n");

                if (chkAutoReplay.Checked)
                {
                    if (HandleCommand(strToRead))
                        return; // 已处理

                    // SendCommand(strToRead);
                    btnSend_Click(null, EventArgs.Empty);
                }
            }));
        }

        private bool HandleCommand(string cmd)
        {
            if (cmd == "!<S>")
            {
                double seconds = dtpFirstRunTime.Value.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                SendCommand("!<S" + Math.Floor(seconds) + ">");
                return true;
            }
            if (cmd == "!<a>")
            {
                SendCommand("!<aLancet01>");
                return true;
            }
            // LED亮度
            if (cmd.StartsWith("!<C"))
            {
                var ledB = cmd.Substring(3, 1)[0] - '0';
                this.LedBrightness = ledB;
            }

            return false;
        }

        private void SendCommand(string cmd)
        {
            serialPort.Write(cmd);
            rtbOutput.AppendText("send:" + cmd + "\r\n");
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            var cmd = cmbCommand.SelectedValue != null ? (string)cmbCommand.SelectedValue : cmbCommand.Text.Trim();
            if (cmd.Length > 0)
            {
                SendCommand(ReBuildLedCommand(cmd));
            }
        }

        private string ReBuildLedCommand(string cmd)
        {
            if (!cmd.StartsWith("!<") || cmd.Length != 26)
                return cmd;

            var prefix = cmd.Substring(0, 24);
            return prefix + LedBrightness + ">";
        }

        private List<KeyValuePair<string, string>> CreateCommands()
        {
            var commands = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("!<aLancet01>", "联机：!<aLancet01>"),
                new KeyValuePair<string, string>("!<B101543926219Na1234b010>", "a1;LED:0;耗材:01;旋转：0"),
                new KeyValuePair<string, string>("!<B101543926219Oa1234b114>", "a1;LED:4;耗材:11;旋转：90"),
                new KeyValuePair<string, string>("!<B111543926219Pa1234b884>", "a1;LED:4;耗材:88;旋转：180"),
                new KeyValuePair<string, string>("!<B121543926219Qa1234bFF5>", "a1;LED:5;耗材:FF;旋转：270"),
                new KeyValuePair<string, string>("!<B101543926219OA1234b114>", "A1;LED:4;耗材:11;旋转：90"),
                new KeyValuePair<string, string>("!<B111543926219PA1234b884>", "A1;LED:4;耗材:88;旋转：180"),
                new KeyValuePair<string, string>("!<B120543926219QA1234bFF5>", "A1;LED:5;耗材:FF;旋转：270;过期"),
            };

            var mySts = new GenericReceivedInstrumentState
            {
                VideoRotate = (byte)'N',
                HcSerialNo = null,
                HcUsedTime = null,
                LedBrightness = 0,
                ErrorCode = 0,
                FactoryTime = DateTime.Now,
                EndoscopicConnected = true
            };
            var bytes = mySts.EncodePacket();
            var testStr = $"!<B{Encoding.ASCII.GetString(bytes)}>";
            commands.Add(new KeyValuePair<string, string>(testStr, "测试"));

            return commands;
        }


        private int LedBrightness
        {
            get
            {
                if (int.TryParse(TxtLedBrightness.Text, out var b))
                    return b;
                return 3;
            }
            set
            {
                TxtLedBrightness.Text = value.ToString();
                ChkLedSts.Checked = value > 0;
            }
        }

        private void CmbCommand_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void ChkAutoReplay_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void ChkLedSts_CheckedChanged(object sender, EventArgs e)
        {
            LedBrightness = ChkLedSts.Checked ? 3 : 0;
        }

        private void BtnCap_Click(object sender, EventArgs e)
        {
            SendCommand("!<P1>");
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            rtbOutput.Text = string.Empty;
        }
    }
}
